import os

from flask import Blueprint, render_template, request, redirect, flash, current_app, jsonify, url_for
from werkzeug.utils import secure_filename
from .get_data.shanjiu_ai import ai_start
from .ai_l import photos_down
from .get_img import get_image_names
from sqlalchemy import create_engine
import pandas as pd
import zhipuai

blue = Blueprint('pixiv', __name__)
folder_file = "./vilipixiv/static/img_top20"
image_names = get_image_names(folder_file)
p = 0


@blue.route('/')
def index():
    num_loaded_images = 20
    loaded_count = 0
    load_more_count = 20
    now_num = loaded_count + load_more_count
    return render_template('index.html', image_names=image_names, loaded_count=loaded_count,
                           load_more_count=load_more_count, now_num=now_num, num_loaded_images=num_loaded_images)


@blue.route('/post')
def post():
    image_name = request.args.get('image_name')
    engine = create_engine('mysql+pymysql://root:2980408675@localhost/vilipixiv')
    img_mysql_name = image_name.split('.')[0]
    # print(img_mysql_name)
    # print('*********************************************************************************')
    df_table = pd.read_sql(
        sql='select `autor`,`like_count`,`time`,`tag`,`url` from img_information_deal_name where name = %s', con=engine,
        params=(img_mysql_name,))
    # print(df_table["autor"].values)
    if not df_table["autor"].values:
        # print(img_mysql_name[:-1])
        df_table = pd.read_sql(
            sql='select `autor`,`like_count`,`time`,`tag`,`url` from img_information_deal_name where name = %s',
            con=engine, params=(img_mysql_name[:-1],))
    # print("来自数据库:", df_table["autor"].values)
    illegal_chars = r'[<>:"/[]\x00-\x1F]'
    img_author = str(df_table["autor"].values[0])
    like_count = str(df_table["like_count"].values[0])
    time_img = str(df_table["time"].values[0])
    tag = str(df_table["tag"].values[0])
    img_url = str(df_table["url"].values[0])
    return render_template('post.html', image_name=image_name, img_author=img_author, like_count=like_count,
                           time_img=time_img, tag=tag, img_url=img_url)


page = 0


@blue.route('/images', methods=['GET', 'POST'])
def get_images():
    global p
    p += 20
    # 返回一组图片URL或其他相关数据
    image_more_name = image_names[p:p + 20]
    return jsonify(image_more_name)


@blue.route('/encoded_url/<path:encoded_url>')
def encoded_url(encoded_url):
    print('*********************************************************************************')
    print(encoded_url)
    image_name = str(encoded_url)
    engine = create_engine('mysql+pymysql://root:2980408675@localhost/vilipixiv')
    img_mysql_name = image_name.split('.')[0]
    print('完成的', img_mysql_name)

    # print(df_table["autor"].values)
    df_table = pd.read_sql(
        sql='select `autor`,`like_count`,`time`,`tag`,`url` from img_information_deal_name where name = %s',
        con=engine, params=(img_mysql_name[:-1],))
    if not df_table["autor"].values:
        # print(img_mysql_name[:-1])
        df_table = pd.read_sql(
            sql='select `autor`,`like_count`,`time`,`tag`,`url` from img_information_deal_name where name = %s',
            con=engine,
            params=(img_mysql_name,))
    img_author = str(df_table["autor"].values[0])
    like_count = str(df_table["like_count"].values[0])
    time_img = str(df_table["time"].values[0])
    tag = str(df_table["tag"].values[0])
    img_url = str(df_table["url"].values[0])
    return render_template('post.html', image_name=image_name, img_author=img_author, like_count=like_count,
                           time_img=time_img, tag=tag, img_url=img_url)


@blue.route('/wanjun')
def ranktl():
    return render_template('ranktl.html')


@blue.route('/api', methods=['POST'])
def sse_invoke_example_from_flask():
    zhipuai.api_key = "41b03c76ccf20688598aecb77f0fd1c1.CvmGivtVH0tie7IO"
    user_say = request.json.get('user_say')  # 从请求中获取用户输入
    if user_say:
        try:
            response = zhipuai.model_api.sse_invoke(
                model="chatglm_pro",
                prompt=[{"role": "user", "content": user_say}],
                top_p=0.7,
                temperature=0.9,
            )
            data = []
            for event in response.events():
                if event.event == "add":
                    data.append(event.data)
                elif event.event == "error" or event.event == "interrupted":
                    data.append(event.data)
                elif event.event == "finish":
                    data.append(event.data)
                    print(event.meta)
                else:
                    data.append(event.data)
            return jsonify(data)  # 以JSON形式返回结果
        except Exception as e:
            return jsonify({'error': str(e)})  # 如果有异常，返回错误信息
    else:
        return jsonify({'error': 'No user input received.'}), 400  # 如果未收到用户输入，返回错误响应


@blue.route('/laoluotuo/')
def upload_file():
    return render_template('laoluotuo.html')


def process_image(image_path):
    # 在这里添加百度AI处理图片的代码
    # 返回处理后的图片路径
    processed_image_path = 'APP/static/downloads/photos'  # 这里假设处理后的图片保存路径
    return processed_image_path


@blue.route('/uploads/', methods=['GET', 'POST'])
def fn1():
    app = current_app._get_current_object()  # 获取当前flask对象
    if request.method == 'POST':
        f = request.files['photo']  # request.files 是一个字典
        # print(request.files)
        # __init__.py中设置了  app.config['UPLOAD_FOLDER'] 文件上传路径
        save_path = os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename))
        f.save(save_path)  # APP/static/uploads/photos/4cfa84eef01f3a29b50dc9159f25bc315e607c56.jpg

        uploaded_image_path = os.path.join(app.config['DOWN_FOLDER'], secure_filename(f.filename))
        processed_image_path = process_image(uploaded_image_path)
        print(uploaded_image_path)
        print(processed_image_path)
        photos_down(save_path, uploaded_image_path)
        # time.sleep(1)

        return render_template('laoluotuo.html', file_path=save_path.replace('vilipixiv/static', ''),
                               processed_image=uploaded_image_path.replace('vilipixiv/static', ''))

    else:

        return render_template('laoluotuo.html')

@blue.route('/canzhu_p1')
def canzhu_p1():
    return render_template('canzhu_one.html')


@blue.route('/canzhu_p2')
def canzhu_p2():
    return render_template('canzhu_two.html')


@blue.route('/finally_daping')
def daping():
    return render_template('最最最最终大屏.html')


@blue.route('/sj_ai/')
def ai_html():
    return render_template('profile_sj.html')


@blue.route('/ai/', methods=['GET', 'POST'])
def sj_ai():
    try:
        app = current_app._get_current_object() # 获取当前flask对象
        if request.method == 'POST':
            f = request.files['photo'] # request.files 是一个字典
            # print(request.files)
            # __init__.py中设置了  app.config['UPLOAD_FOLDER'] 文件上传路径
            save_path =os.path.join(app.config['UPLOAD_FOLDER'], secure_filename(f.filename))
            f.save(save_path)  # APP/static/uploads/photos/4cfa84eef01f3a29b50dc9159f25bc315e607c56.jpg
            data = ai_start(save_path)
            print(data)
            return  render_template('profile_sj.html', file_path=save_path.replace('vilipixiv/static',''), data = str(data))

        else:

            return render_template('profile_sj.html')
    except:
        return render_template('profile_sj.html')